Variables

 

Variables

  • In programming, data that can be used and altered throughout a program is stored in variables.
  • These are designated memory areas where you can put variables that vary while the program executes. 
  • Variables in C++ require declaration before they can be utilized; this declaration must include the variable name and data type.



     Following rules must be followed for identifiers:

     The first character must always be an alphabet or an underscore.

     It should be formed using only letters, numbers, or underscore.

      uppercase and lowercase are distinct

     A keyword cannot be used as a variable name.

     It should not contain any whitespace character.

     The name must be meaningful.

Declaring the variable

To create a variable, you must specify the data type and assign it a value:

Syntax

Data Type variable = value;

Example 1: Basic Variable Declaration and Initialization

#include <iostream>

using namespace std;

int main() {

    // Declare an integer variable

    int age = 25; // 'age' is a meaningful name for a variable that stores an age

    // Declare a double variable

    double price = 19.99; // 'price' clearly indicates that this variable holds a price value

    // Output the values of the variables

    cout << "Age: " << age << endl;

    cout << "Price: " << price << endl;

    return 0;

}

Example 2: Using Variables in Calculations

#include <iostream>
using namespace std;

int main() {
    // Declare two integer variables
    int length = 10; // 'length' is a meaningful name for a variable that stores length
    int width = 5; // 'width' is a meaningful name for a variable that stores width

    // Calculate the area of a rectangle
    int area = length * width;

    // Output the result
    cout << "The area of the rectangle is: " << area << " square units" << endl;

    return 0;
}


Post a Comment

0 Comments